package com.ecds.monitor;

import java.io.IOException;

import com.ecds.monitor.helper.SystemHelper;
import com.ecds.monitor.http.GetHttpHtmlThread;
import com.ecds.monitor.https.GetHtmlThread;

public class Web {

	public static final int timeOutMs = 20000;
	public static final int retry = 3;

	/*
	 * 调用bat生成的exe
	 */
	public static void runexe() {
		String exeLocal = MainServer.rb.getString("monitoring.exeLocal");
		Runtime rt = Runtime.getRuntime();// java的API，获得一个对象
		try {
			rt.exec(exeLocal);// 找到这个路径，直接调用即可
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 验证获取到的HTML，如果没有结束符，则认为异常
	 */
	public static void checkHtml() {
		String message = MainServer.rb.getString("monitoring.sendMessage");
		try {
			if("true".equals(MainServer.rb.getString("monitoring.url.check"))){
				String urlStr = MainServer.rb.getString("monitoring.url");
				String html = getHttpsHtml(urlStr);
				if (!html.contains("</html>")) {
					System.out.println("失败了");
					// 远程监控，发现异常发短信
					SystemHelper.testSendSMS(message);
					// 本地监控，发现异常，自动切换ng
					// runexe();
				}
			}
			if("true".equals(MainServer.rb.getString("monitoring.ips.check"))){
				String portUrl = MainServer.rb.getString("monitoring.ips");
				if(SystemHelper.notNullOrEmpty(portUrl)){
					String[] url = portUrl.split(";");
					for(int i=0; i<url.length; i++){
						if(SystemHelper.notNullOrEmpty(url[i])){
							String gethtml = getHttpHtml(url[i]);
							if (!gethtml.contains("</html>")) {
								System.out.println("失败了" + url[i]);
								// 远程监控，发现异常发短信
								SystemHelper.testSendSMS(url[i] + message);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			System.out.println("异常，失败了");
			SystemHelper.testSendSMS(message);
			// runexe();
		}
	}

	/**
	 * 调用https地址，返回xml
	 * 
	 * @return
	 */
	public static String getHttpsHtml(String urlStr) {
		int retryCount = 0;
		while (true) {
			try {
				GetHtmlThread thread = new GetHtmlThread(urlStr);
				thread.start();
				thread.join(timeOutMs);
				if (!thread.isAlive()) {
					return thread.html;
				} else {
					thread.interrupt();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			retryCount++;
			if (retryCount > retry) {
				throw new RuntimeException("尝试" + (retry - 1) + " 次后失败");
			}
		}
	}
	
	public static String getHttpHtml(String urlStr) {
		int retryCount = 0;
		while (true) {
			try {
				GetHttpHtmlThread thread = new GetHttpHtmlThread(urlStr);
				thread.start();
				thread.join(timeOutMs);
				if (!thread.isAlive()) {
					return thread.html;
				} else {
					thread.interrupt();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			retryCount++;
			if (retryCount > retry) {
				throw new RuntimeException("尝试" + (retry - 1) + " 次后失败");
			}
		}
	}
}
